﻿#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    InitUI();
    /*-------------------------------------------------------------------*/
    sendTimer = new QTimer(this);
    connect(sendTimer,&QTimer::timeout,this,&Widget::on_SnedData_clicked); //循环定时发送
    findComTimer = new QTimer(this);
    connect(findComTimer,&QTimer::timeout,this,&Widget::Refresh_ComList); //刷新串口列表
    findComTimer->start(500);
    /*-------------------------------------------------------------------*/
    objSerial = new Serial;
    dvThread = new QThread(this);
    objSerial->moveToThread(dvThread);
    connect(dvThread,&QThread::finished,objSerial,&QObject::deleteLater);

    connect(this,&Widget::openSerial,objSerial,&Serial::OpenSerial);
    connect(this,&Widget::closeSerial,objSerial,&Serial::CloseSerial);
    connect(this,&Widget::sendData,objSerial,&Serial::SerialWrite);
    connect(objSerial,&Serial::recive,this,&Widget::showRecive);

    dvThread->start();
}

Widget::~Widget()
{
    emit closeSerial();
    if(dvThread->isRunning())
    {
        dvThread->quit();
        if(!dvThread->wait(3000))
        {
            dvThread->terminate();
        }
    }
    delete ui;
}

void Widget::InitUI()
{
    /*---加载皮肤---*/
    QFile file(":/qss/psblack.css");
    file.open(QFile::ReadOnly);
    QString styleSheet = QString::fromLatin1(file.readAll());
    QString paletteColor = styleSheet.mid(20, 7);
    qApp->setPalette(QPalette(QColor(paletteColor)));
    qApp->setStyleSheet(styleSheet);
    /*---界面初始状态---*/
    ui->TimeDisplay->setCheckState(Qt::Checked);
    ui->AutoSwitchLine->setCheckState(Qt::Checked);
    ui->ReciveCountLabel->setText("累计接收：0");
    ui->SendCountLabel->setText("累计发送：0");
    ui->SnedData->setEnabled(false);
    ui->SerialClose->setEnabled(false);
}
void Widget::Refresh_ComList()
{
    QList<QSerialPortInfo> Ports = QSerialPortInfo::availablePorts();
    if(Ports.count() != ui->SerialList->count())
    {
        //先清除原有的item
        ui->SerialList->clear();
        foreach (const QSerialPortInfo &info, Ports)
        {
            //将串口号添加到comboBox_Serial_num控件
            ui->SerialList->addItem(info.portName());
        }
    }
}

void Widget::on_SerialOpen_clicked()
{
    emit openSerial(
                ui->SerialList->currentText(),
                ui->BaudrateList->currentText().toInt(),
                ui->DataBitsList->currentText().toInt(),
                ui->StopBitsList->currentIndex(),
                ui->ParityList->currentIndex(),
                ui->FlowControlList->currentIndex()
                );
    DisableSelection();
    findComTimer->stop();
}
void Widget::on_SerialClose_clicked()
{
    emit closeSerial();
    EnableSelection();
    findComTimer->start(500);
}

void Widget::on_ClearRecive_clicked()
{
    ui->ComContent->clear();
}

void Widget::on_SnedData_clicked()
{
    //读取当前输入的字符串
    QString StrToSend = ui->DataToSend->toPlainText();
    //判断是否勾选发送换行
    if(ui->SendNewLine->isChecked())
    {
        StrToSend += "\r\n";
    }
    //判断是否勾选16进制发送
    if(ui->SendHEX->isChecked())
    {
        emit sendData(QByteArray::fromHex(StrToSend.toUtf8()));
    }
    else
    {
        emit sendData(StrToSend.toUtf8());
    }
    SendCount += StrToSend.length();
    ui->SendCountLabel->setText("累计发送：" + QString::number(SendCount));
    if(ui->TimeDisplay->isChecked())//如果勾选了时间显示
    {
        QDateTime current_date_time =QDateTime::currentDateTime();
        QString current_date_str = current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz") + "\t发";
        ui->ComContent->append(current_date_str);
    }
    ui->ComContent->append(StrToSend);
}

void Widget::showRecive(const QByteArray& Recive_msg)
{
    if(Recive_msg.size() != 0)
    {
        ReciveCount += Recive_msg.size();
        ui->ReciveCountLabel->setText("累计接收：" + QString::number(ReciveCount));
        if(ui->TimeDisplay->isChecked())//如果勾选了时间显示
        {
            ui->ComContent->append(QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz\t收"));
        }
        if(ui->DisplayHEX->isChecked())//如果勾选了16进制显示
        {
            ui->ComContent->append(Recive_msg.toHex(' '));
        }
        else
        {
            ui->ComContent->append(QString::fromUtf8(Recive_msg));
        }
        if(ui->AutoSwitchLine->isChecked())//如果勾选了自动换行
        {
            ui->ComContent->append("");
        }
    }
}
void Widget::on_SendClear_clicked()
{
    ReciveCount = 0;
    ui->ReciveCountLabel->setText("累计接收：" + QString::number(ReciveCount));
    SendCount = 0;
    ui->SendCountLabel ->setText("累计发送：" + QString::number(SendCount));
}

void Widget::on_OpenFile_clicked()
{
    QString file_path = QFileDialog::getOpenFileName(NULL,"请选择txt文件","","");
    if(file_path.isEmpty())
    {
        QMessageBox::warning(0,"提示","未选择文件");
        return;
    }
    else
    {
        QFile txt_file(file_path);
        if (!txt_file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QMessageBox::warning(0,"错误","打开文件失败");
        }
        else
        {
            ui->DataToSend->setText(txt_file.readAll());
            txt_file.close();
        }
    }
}

void Widget::on_LoopSend_clicked()
{
    if(ui->LoopSend->isChecked())
    {
        sendTimer->start(ui->LoopSendPeriod->text().toInt());
    }
    else
    {
        sendTimer->stop();
    }
}

void Widget::on_SaveData_clicked()
{
    if(ui->ComContent->toPlainText().length() > 0)
    {
        QDateTime current_date_time =QDateTime::currentDateTime();
        QString FilePath = qApp->applicationDirPath() + current_date_time.toString("/yyyy年MM月dd日hh-mm-ss") + ".txt";
        QFile RecordFile(FilePath);
        if (RecordFile.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            RecordFile.write(ui->ComContent->toPlainText().toLocal8Bit());  //写入文件
            RecordFile.close();
            QMessageBox::information(0,"提示","保存成功！");
        }
        else
        {
            QMessageBox::warning(0,"错误！","写入文件失败！");
        }
    }
}

//关闭串口时启用选项
void Widget::EnableSelection()
{
    ui->SerialList->setEnabled(true);
    ui->BaudrateList->setEnabled(true);
    ui->DataBitsList->setEnabled(true);
    ui->StopBitsList->setEnabled(true);
    ui->ParityList->setEnabled(true);
    ui->FlowControlList->setEnabled(true);
    ui->SerialOpen->setEnabled(true);
    ui->SerialClose->setEnabled(false);
    ui->SnedData->setEnabled(false);
}
//打开串口时禁用选项
void Widget::DisableSelection()
{
    ui->SerialList->setEnabled(false);
    ui->BaudrateList->setEnabled(false);
    ui->DataBitsList->setEnabled(false);
    ui->StopBitsList->setEnabled(false);
    ui->ParityList->setEnabled(false);
    ui->FlowControlList->setEnabled(false);
    ui->SerialOpen->setEnabled(false);
    ui->SerialClose->setEnabled(true);
    ui->SnedData->setEnabled(true);
}


void Widget::on_ClearSend_clicked()
{
    ui->DataToSend->clear();
}
